export default class Canvas {
  constructor(selector, context, dimensions = { x: 0, y: 0 }) {
    const self = this
    window.requestAnimationFrame = (() => {
      return (
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback) {
          window.setTimeout(callback, 1000 / 60)
        }
      )
    })()

    if (selector) {
      this.el = document.querySelector(selector)
    } else {
      this.el = document.createElement('canvas')
      document.body.appendChild(this.el)
    }

    this.ctx = this.el.getContext(context) || this.el.getContext('2d')
    this.dimensions = dimensions
    this.center = {
      x: this.dimensions.x * 0.5,
      y: this.dimensions.y * 0.5,
    }

    this.resize()
    window.addEventListener('resize', self.resize.bind(self))
  }

  hsla(h, s, l, a) {
    return `hsla(${h},${s},${l},${a})`
  }

  fill(x, y, width, height, fill = 'rgba(0,0,0,1)') {
    this.ctx.fillStyle = fill
    this.ctx.fillRect(x, y, width, height)
  }

  drawLine(x1, y1, x2, y2, stroke = 'rgba(255,255,255,1)', strokeWidth = 2) {
    this.ctx.beginPath()
    this.ctx.moveTo(x1, y1)
    this.ctx.lineTo(x2, y2)
    this.ctx.strokeStyle = stroke
    this.ctx.lineWidth = strokeWidth
    this.ctx.stroke()
    this.ctx.closePath()
  }

  drawArc(x, y, r, fill, stroke = 'rgba(200,0,0,1)', strokeWidth = 2) {
    this.ctx.beginPath()
    this.ctx.arc(x, y, r, 0, Math.PI * 2)
    this.ctx.fillStyle = fill
    this.ctx.fill()
    if (stroke) {
      this.ctx.strokeStyle = stroke
      this.ctx.lineWidth = strokeWidth
      this.ctx.stroke()
    }
    this.ctx.closePath()
  }

  resize() {
    this.el.width = this.dimensions.x = window.innerWidth
    this.el.height = this.dimensions.y = window.innerHeight
    this.center = {
      x: this.dimensions.x * 0.5,
      y: this.dimensions.y * 0.5,
    }
  }
}
